<template>
  <a-form class="smart-query-form" :model="queryParams" ref="queryRef" layout="inline" v-show="showSearch"
    :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
    <a-row class="smart-query-form-row">
      <a-form-item label="分类名称" name="name" class="smart-query-form-item">
        <a-input v-model:value="queryParams.name" placeholder="请输入流程分类名称" allowClear @pressEnter="handleQuery" />
      </a-form-item>
      <a-form-item label="分类编码" name="code" class="smart-query-form-item">
        <a-input v-model:value="queryParams.code" placeholder="请输入分类编码" allowClear @pressEnter="handleQuery" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button-group>
          <a-button type="primary" @click="handleQuery" v-privilege="'flow:flow_classify:query'">
            <template #icon>
              <SearchOutlined />
            </template>
            搜索
          </a-button>
          <a-button @click="resetQuery" v-privilege="'flow:flow_classify:query'">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card size="small" :bordered="false" :hoverable="true">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button type="primary" @click="handleAdd" v-hasPermi="['flow:flow_classify:add']">
          <template #icon>
            <PlusOutlined />
          </template>
          新增
        </a-button>

        <a-button type="primary" :disabled="selectedRowKeyList.length != 1" @click="handleUpdate"
          v-hasPermi="['flow:flow_classify:update']">
          <template #icon>
            <EditOutlined />
          </template>
          修改
        </a-button>

        <a-button type="primary" danger :disabled="selectedRowKeyList.length === 0" @click="handleDelete"
          v-hasPermi="['flow:flow_classify:delete']">
          <template #icon>
            <DeleteOutlined />
          </template>
          删除
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.FLOW.MODEL" :refresh="getList" />
      </div>
    </a-row>

    <a-table size="small" :dataSource="categoryList" :pagination="false" rowKey="id"
      :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
      <a-table-column title="流程分类id" dataIndex="id" align="center" />
      <a-table-column title="分类名称" dataIndex="name" align="center" />
      <a-table-column title="分类编码" dataIndex="code" align="center" />
      <a-table-column title="备注" dataIndex="remark" align="center" />
      <a-table-column title="操作" align="center" width="180">
        <template #default="{ record }">
          <a-space>
            <a-button type="link" @click="handleUpdate(record)" v-hasPermi="['flow:flow_classify:update']">
              <template #icon>
                <EditOutlined />
              </template>
              修改
            </a-button>
            <a-button type="link" @click="handleDelete(record)" v-hasPermi="['flow:flow_classify:delete']">
              <template #icon>
                <DeleteOutlined />
              </template>
              删除
            </a-button>
          </a-space>
        </template>
      </a-table-column>
    </a-table>
    <div class="smart-query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize" v-model:current="queryForm.pageNum" v-model:pageSize="queryForm.pageSize"
        :total="total" @change="getList" @showSizeChange="getList" :show-total="(total) => `共${total}条`" />
    </div>
  </a-card>

  <!-- 添加或修改流程分类对话框 -->
  <a-modal :title="title" v-model:open="open" width="600px" @ok="submitForm" @cancel="cancel">
    <a-form ref="categoryRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="分类名称" name="name">
        <a-input v-model:value="form.name" placeholder="请输入流程分类名称" />
      </a-form-item>
      <a-form-item label="分类编码" name="code">
        <a-input v-model:value="form.code" placeholder="请输入分类编码" />
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-textarea v-model:value="form.remark" placeholder="请输入内容" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup name="Category">
import { getCurrentInstance, ref, reactive, toRefs } from "vue";
import { message, Modal } from 'ant-design-vue';
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@ant-design/icons-vue';
import { categoryApi } from "/@/api/business/flowable/category";
import { smartSentry } from '/@/lib/smart-sentry';
import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
import { SmartLoading } from '/@/components/framework/smart-loading';
import _ from 'lodash';

const { proxy } = getCurrentInstance();

const categoryList = ref([]);
const open = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// const data = reactive({
//   form: {},
//   queryParams: {
//     pageNum: 1,
//     pageSize: 10,
//     name: null,
//     code: null,
//   },
//   rules: {
//     name: [
//       { required: true, message: "分类名称不能为空", trigger: "blur" }
//     ],
//     code: [
//       { required: true, message: "分类编码不能为空", trigger: "blur" }
//     ]
//   }
// });

const queryParams = {
  pageNum: 1,
  pageSize: 10,
  name: undefined,
  code: undefined,
};

const rules = {
  name: [
    { required: true, message: "分类名称不能为空", trigger: "blur" }
  ],
  code: [
    { required: true, message: "分类编码不能为空", trigger: "blur" }
  ]
}

const form = ref([])
// 查询表单form
const queryForm = reactive(_.cloneDeep(queryParams));

// ---------------------------- 表格列 ----------------------------

const columns = ref([]);

// const { queryParams, form, rules } = toRefs(data);

/** 查询流程分类列表 */
async function getList() {
  SmartLoading.show()
  try {
    let categoryModel = await categoryApi.listCategory(queryForm)
    // let categoryModel = await categoryApi.queryCategory(queryForm)
    categoryList.value = categoryModel.data.rows
    total.value = categoryModel.data.total
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide()
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    code: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  // proxy.resetForm("categoryRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  // queryParams.value.pageNum = 1;
  queryForm.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selectedRowKeys) {
  ids.value = selectedRowKeys;
  single.value = selectedRowKeys.length !== 1;
  multiple.value = !selectedRowKeys.length;
}

// 选择表格行
const selectedRowKeyList = ref([]);

function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加流程分类";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  let _id = selectedRowKeyList.value
  if (row.id) {
    _id = row.id
  }
  try {
    let response = await categoryApi.getCategory(_id)
    form.value = response.data;
    open.value = true;
    title.value = "修改流程分类";
  } catch (e) {
    smartSentry.captureError(e)
  }
}

/** 提交按钮 */
function submitForm() {
  categoryRef.value.validate().then(async () => {
    try {
      if (form.value.id) {
        let res = await categoryApi.updateCategory(form.value)
        if (res.data === -1) {
          message.warning("已存在分类名称或分类编码")
        } else {
          message.success("修改成功");
          open.value = false;
          getList();
        }
      } else {
        let res = await categoryApi.addCategory(form.value)
        if (res.data === -1) {
          message.warning("已存在分类名称或分类编码")
        } else {
          message.success("新增成功");
          open.value = false;
          getList();
        }
      }
    } catch (e) {
      smartSentry.captureError(e)
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  let _ids = selectedRowKeyList.value
  if (row.id) {
    _ids = row.id
  }
  Modal.confirm({
    title: '确认',
    content: `是否确认删除流程分类编号为"${_ids}"的数据项？`,
    async onOk() {
      return await categoryApi.deleteCategory(_ids).then(() => {
        getList();
        message.success("删除成功");
        if (!row.id) {
          selectedRowKeyList.value = []
        }
      });
    }
  });
}

const categoryRef = ref(null);

getList();
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>
